<?php
/*
Primary Author: Alex Arey
Secondary: Derek Shue, Sean Margison
Updated: 12/10/2011
Module Description: The Partner controller is responsible for partner actions including
submitting volunteer and internship requests and browsing their current and past requests.
*/
class PartnerController extends Zend_Controller_Action
{
	/**
	* Init initializes the controller and verifies that the user has a session.
	*/
    public function init()
    {
        $auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
    }
    
    /**
    * index action of the controller assumes myinternships as action.
    */
    public function indexAction(){
		return $this->_helper->redirector('myinternships');
    }

	/**
	* Myinternships actions displays current and future positions for the
	* partner.
	*/
    public function myinternshipsAction(){
        $auth = Zend_Auth::getInstance(); 
		$partnerID = $auth->getIdentity()->getUID();
		$positionQuery = new Application_Model_InternshipQuery();
		$positions = $positionQuery->getInternships_CP($partnerID);
		$this->view->positions = $positions;	
    }
    
    /**
    * Submit internships action handles the Zend_Form for submitting a new
    * internship request.
    */
    public function submitinternshipAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		
		$cq = new Application_Model_ContactsQuery();
		$contactsraw = $cq->getContacts_CP($partnerID);
		$contacts = array();
		foreach($contactsraw as $contact)
		{
			$contacts[] = $contact['FIRSTNAME'] . " " . $contact['LASTNAME'];
		}
		if(sizeof($contacts) == 0)
			$contacts[0] = "";
		$form = new Application_Form_PartnerCreateIntern(array('contacts'=>$contacts));
		
		$term = new Application_Model_Term();
		$termname = $term->getCurrentOpenTermStr('cpintern');
		if(!$termname){
			$this->view->noTerm = true;
			return;
		}
		$this->view->term = $termname;
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
		    $formData = $this->getRequest()->getPost();
		    if ($form->isValid($formData)) {
				$term = new Application_Model_Term();
				$itrn = new Application_Model_DbTable_InternPositions();
				$posid = $itrn->addInternPosition(
					$partnerID,//cpid
					$form->getValue('title'),//internship name
					$term->parseDateToOracle($form->getValue('startDate')),//start date
					$term->parseDateToOracle($form->getValue('endDate')),//end date
					$form->getValue('responsibilities'),//responsibilities
					$form->getValue('eduGoals'),//education goals
					$this->requirementsString($form->getValue('requirements')),//requirements
					$form->getValue('majors'),//preferred majors/programs
					$form->getValue('importance'),//major importance
					$contacts[$form->getValue('supervisor')],//supervisor
					$form->getValue('isContact'),//supervisor is contact
					$form->getValue('structure'),
					$form->getValue('support'),
					$form->getValue('staff'),
					$form->getValue('otherInterns'),
					$form->getValue('needDesc'),
					$form->getValue('benefits'),
					$form->getValue('numRequesting'),//positions requested
					0,
					$term->getCurrentOpenTermStr('cpintern')
				);
				
				$interntagsmodel = new Application_Model_DbTable_Interntags();
				$associatedtags = $form->getValue('TAGNAMES');
				if($associatedtags)
				foreach($associatedtags as $tag){
					$interntagsmodel->addInterntag($posid, $tag);
				}
				
											
				
				return $this->_helper->redirector('myinternships');						 
		    }
		}
    }

	/**
	* RequirementsString is used for submitting internship applications to 
	* take the associative array returned from the form and converting it
	* to a '|' delimited string of values.
	*/
    public function requirementsString($req){
		$retstr = "";
		foreach($req as $key => $val){
			$retstr = $retstr . " | " . $val;
		}
		return $retstr;
	}
	/**
	*Browse Internships handles browsing and searching for all volunteer positions.
	*/
    public function browseinternshipsAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		$form = new Application_Form_Search();
		$this->view->form = $form;

		$positionQuery = new Application_Model_InternshipQuery();
		//set defaults
		$termModifier = 'ns';
		$term = '';
		$name = '';
		$date = new Zend_Date();
		//overwrite defaults with form data
		if ($this->getRequest()->isPost()) {
		        $formData = $this->getRequest()->getPost();
		        if ($form->isValid($formData)) {
		        	if($form->getValue('YEAR') == ""){
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $date->get(Zend_Date::YEAR));
		        	}else{
		        		$term = array('term'=>$form->getValue('TERM') , 'year' => $form->getValue('YEAR'));
		        	}		
		            $termModifier = $form->getValue('MODIFIER');
					$name = $form->getValue('NAME');								 
		        }
		}
		$positions = $positionQuery->selectInternships_CP($partnerID, $term, $termModifier, $name);
		$this->view->positions = $positions;
    }


	/**
	MyVolunteers provides the current-term summary view of volunteer positions for partners.
	*/
    public function myvolunteersAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}
		else{
			$this->_helper->redirector('index','index');
			return;
		}
		$positionQuery = new Application_Model_VolunteerQuery();
		$positions = $positionQuery->getVRs_CP($partnerID);
		$this->view->positions = $positions;	
    }

	/**
	Submitvolunteer displays and processes the form for submitting volunteer requests
	*/
    public function submitvolunteerAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		
		$cq = new Application_Model_ContactsQuery();
		$contactsraw = $cq->getContacts_CP($partnerID);
		$contacts = array();
		foreach($contactsraw as $contact)
		{
			$contacts[] = $contact['FIRSTNAME'] . " " . $contact['LASTNAME'];
		}
		if(sizeof($contacts) == 0)
		$contacts[0] = "";

		$form = new Application_Form_PartnerCreateVolunteer(array('contacts'=>$contacts));
		$term = new Application_Model_Term();
		$termname = $term->getCurrentOpenTermStr('cpvol');
		if(!$termname){
			$this->view->noTerm = true;
			return;
		}
		$this->view->term = $termname;
		$this->view->form = $form;
		if ($this->getRequest()->isPost()) {
		    $formData = $this->getRequest()->getPost();
		    if ($form->isValid($formData)) {
				$term = new Application_Model_Term();
				$itrn = new Application_Model_DbTable_VolunteerRequests();
				$req = $form->getValue('requirements');
				$super = $contacts[$form->getValue('sitesupervisor')];//site supervisor
				//multilist element for requirements returns an array. 
				//This sets y/n variables to go into database columns.
				$reqvehicle = (in_array('REQVEHICLE',$req))?'y':'n';
				$reqbgcheck = (in_array('REQBGCHECK',$req))?'y':'n';
				$reqheavylifting = (in_array('REQHEAVYLIFTING',$req))?'y':'n';
				$reqinterview = (in_array('REQINTERVIEW',$req))?'y':'n';
				$reqspanish = (in_array('REQSPANISH',$req))?'y':'n';
				$reqtbtest = (in_array('REQTBTEST',$req))?'y':'n';
				$vrid = $itrn->addVolunteerRequest(
					$partnerID,//cpid
					$form->getValue('POSITIONTITLE'),//internship name
					$termname,//term
					$form->getValue('DESCRIPTION'),//responsibilities
					$form->getValue('NUMBERREQUESTING'),//education goals
					$reqvehicle,//requirements
					$reqbgcheck,
					$reqheavylifting,
					$reqinterview,
					$reqspanish,
					$reqtbtest,
					$form->getValue('REQOTHERDESC'),//preferred majors/programs
					$super
				);
				
				$requesttagsmodel = new Application_Model_DbTable_Requesttags();
				$associatedtags = $form->getValue('TAGNAMES');
				if($associatedtags)
				foreach($associatedtags as $tag){
					$requesttagsmodel->addRequesttag($vrid, $tag);
				}
						
				
				return $this->_helper->redirector('myvolunteers');						 
		    }
		}
    }

    public function browsevolunteersAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}

		$form = new Application_Form_Search();
		$this->view->form = $form;
		$positionQuery = new Application_Model_VolunteerQuery();
		//set defaults
		$termModifier = 'ns';
		$term = '';
		$name = '';
		//overwrite defaults with form data
		if ($this->getRequest()->isPost()) {
		        $formData = $this->getRequest()->getPost();
		        if ($form->isValid($formData)) {		
					$term = array('term'=>$form->getValue('TERM') , 'year' => $form->getValue('YEAR'));
		            $termModifier = $form->getValue('MODIFIER');
					$name = $form->getValue('NAME');								 
		        }
		}
		$positions = $positionQuery->selectVRs_CP($partnerID, $term, $termModifier, $name);
		$this->view->positions = $positions;
    }

	/**
	Viewinternship displays internship position information for the given information for 'position' get variable
	*/
    public function viewinternshipAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
		//get position data
		$positionQuery = new Application_Model_InternshipQuery();
		try{
			$row = $positionQuery->selectInternship_ID($this->getRequest()->getParam('position'));
			if($row['CPID'] != $partnerID){
				$this->view->position = null;
			}else{
				$this->view->position = $row;
			}
		}catch(Exception $e){
			$this->view->position = null;
		}
		//get applicants for the position
		try{
			$apps = $positionQuery->selectApplicationsForInternship_CP($this->getRequest()->getParam('position'));
			$applications = array();
			if($apps){
				foreach($apps as $app){
					$application = new Application_Model_InternshipApp();
					$application->init($app['APPID']);
					$applications[] = $application;	
				}
			}
			$this->view->applications = $applications;
		}catch(Exception $e){
			$this->view->applications = null;
		}
	}
	
	/**
	Viewvolunteer displays internship position information for the given information for 'position' get variable
	*/
	public function viewvolunteerAction(){
		$auth = Zend_Auth::getInstance(); 
		if($auth->hasIdentity()){
			$partnerID = $auth->getIdentity()->getUID();
		}else{
			$this->_helper->redirector('index','index');
			return;
		}
	//get position data
		$positionQuery = new Application_Model_VolunteerQuery();
		try{
			$row = $positionQuery->selectVR_ID($this->getRequest()->getParam('position'));
			if($row['CPID'] != $partnerID){
				$this->view->position = null;
			}else{
				$this->view->position = $row;
			}
		}catch(Exception $e){
			$this->view->position = null;
		}
	//get applicants for the position
		try{
			$apps = $positionQuery->selectCoursesForVR_ID($row['VRID']);
			$this->view->applicants = $apps;
		}catch(Exception $e){
			$this->view->applicants = null;
		}
	}
	//displays the detailed volunteer request report as a form for editing.
	public function volunteerdetailsAction(){
		$auth = Zend_Auth::getInstance();
		$cpid = $auth -> getIdentity() -> getUID();
		$vrid = $this -> _getParam('position');
		
		$cq = new Application_Model_ContactsQuery();
		$contactsraw = $cq->getContacts_CP($partnerID);
		$contacts = array();
		foreach($contactsraw as $contact)
		{
			$contacts[] = $contact['FIRSTNAME'] . " " . $contact['LASTNAME'];
		}
		if(sizeof($contacts) == 0)
		$contacts[0] = "";

		$form = new Application_Form_PartnerCreateVolunteer(array('contacts'=>$contacts));
		$form->submit->setLabel('Save');
		$this->view->form = $form;
		
		if ($this->getRequest()->isPost()) {
            $formData = $this->getRequest()->getPost();
            if ($form->isValid($formData)) {
            	
				$positiontitle = $form->getValue('POSITIONTITLE');
				$term = $form->getValue('TERM');
				$description = $form->getValue('DESCRIPTION');
				$numberrequesting = $form->getValue('NUMBERREQUESTING');
				
				$req = $form->getValue('requirements');
				$reqvehicle = (in_array('REQVEHICLE',$req))?'y':'n';
				$reqbgcheck = (in_array('REQBGCHECK',$req))?'y':'n';
				$reqheavylifting = (in_array('REQHEAVYLIFTING',$req))?'y':'n';
				$reqinterview = (in_array('REQINTERVIEW',$req))?'y':'n';
				$reqspanish = (in_array('REQSPANISH',$req))?'y':'n';
				$reqtbtest = (in_array('REQTBTEST',$req))?'y':'n';
				
				$reqotherdesc = $form->getValue('REQOTHERDESC');
				
				$request = new Application_Model_DbTable_VolunteerRequests();
				$request->updateVolunteerRequest($vrid ,$cpid,$positiontitle,$term,$description,$numberrequesting,$reqvehicle,$reqbgcheck,$reqheavylifting,$reqinterview,$reqspanish,$reqtbtest,$reqotherdesc);
				
				
            	$requesttagsmodel = new Application_Model_DbTable_Requesttags();
				$existingTags = $requesttagsmodel->getTagsForTerm($vrid);
				$tagsArray = array();
				if($existingTags)
				{
					foreach($existingTags as $tag){
						$tagsArray[] = $tag['TAGNAME'];
					}
				}
				$updateTags = $form->getValue('TAGNAMES');
				if($updateTags)
				{
					$requesttagsmodel->deleteRequesttag($vrid);
					$addTags = array_diff($updateTags, $existingTags);
					
					foreach($addTags as $tag){
						if(!in_array($tag,$existingTags))
							$requesttagsmodel->addRequesttag($vrid, $tag);
					}
				}
				
				$this->_helper->redirector('myvolunteers');
			} else {
				$form->populate($formData);
			}
		} else {
			if($vrid > 0){
				$request = new Application_Model_DbTable_VolunteerRequests();
				$details = $request->getVolunteerRequest("VRID = " . $vrid);
				
				$requesttagsmodel = new Application_Model_DbTable_Requesttags();
				$existingTags = $requesttagsmodel->getTagsForTerm($vrid);
				$tagsArray = array();
				if($existingTags)
				{
					foreach($existingTags as $tag){
						$tagsArray[] = $tag['TAGNAME'];
					}
				}
				$form->getElement('TAGNAMES')->setValue($tagsArray);
				
				$form->populate($details);
				$subarray = array();
				if($details['REQVEHICLE']=='y'){
					$subarray[] = 'REQVEHICLE';
				}
				if($details['REQBGCHECK']=='y'){
					$subarray[] = 'REQBGCHECK';				
				}
				if($details['REQHEAVYLIFTING']=='y'){
					$subarray[] = 'REQHEAVYLIFTING';				
				}
				if($details['REQINTERVIEW']=='y'){
					$subarray[] = 'REQINTERVIEW';				
				}
				if($details['REQSPANISH']=='y'){
					$subarray[] = 'REQSPANISH';				
				}
				if($details['REQTBTEST']=='y'){
					$subarray[] = 'REQTBTEST';				
				}
				$form->getElement('requirements')->setValue($subarray);
			}
		}
	}
	
	/**
	deleterequest deletes the volunteer requests specified by 'vrid'
	*/
	public function deleterequestAction() {
		if ($this -> getRequest() -> isPost()) {
			$del = $this -> getRequest() -> getPost('del');
			if ($del == 'Yes') {
				$vrid = $this -> _getParam('position');
				$request = new Application_Model_DbTable_VolunteerRequests();
				$query = 'VRID = '. $vrid;
				$request->deleteVolunteerRequest($query);
			}

			$this -> _helper -> redirector('myvolunteers');
		} else {
			$vrid = $this -> _getParam('VRID');
			$request = new Application_Model_DbTable_VolunteerRequests();
			$this -> view -> request = $request -> getVolunteerRequest($vrid);
		}
	}
	
	public function viewcoursesAction(){
		
	}
	

}
?>